import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { ChatItem, ThoughtItem, VisionFile, MessageEnd, MessageReplace } from '@/types/app'
import { WorkflowRunningStatus } from '@/types/app'
import type { WorkflowStartedResponse, WorkflowFinishedResponse, NodeStartedResponse, NodeFinishedResponse } from '@/service/base'

export const useChatStore = defineStore('chat', () => {
  // 状态
  const chatList = ref<ChatItem[]>([])
  const currentStreamingMessageId = ref<string | null>(null)
  const accumulatedContent = ref<string>('')
  const isStreaming = ref(false)

  // 计算属性
  const currentStreamingMessage = computed(() => {
    if (!currentStreamingMessageId.value) return null
    return chatList.value.find(item => item.id === currentStreamingMessageId.value)
  })

  // 基础操作
  const setChatList = (list: ChatItem[]) => {
    chatList.value = list
  }

  const addChatItem = (item: ChatItem) => {
    chatList.value.push(item)
  }

  const updateChatItem = (id: string, updates: Partial<ChatItem>) => {
    const index = chatList.value.findIndex(item => item.id === id)
    if (index !== -1) {
      chatList.value[index] = { ...chatList.value[index], ...updates }
    }
  }

  const clearChatList = () => {
    chatList.value = []
    resetStreamingState()
  }

  // 流式数据处理
  const startStreaming = (messageId: string) => {
    currentStreamingMessageId.value = messageId
    accumulatedContent.value = ''
    isStreaming.value = true
    
    // 标记消息为流式状态
    updateChatItem(messageId, { streaming: true })
  }

  const appendStreamingContent = (messageId: string, chunk: string, isFirst = false) => {
    if (currentStreamingMessageId.value !== messageId) {
      console.warn('流式消息ID不匹配:', { current: currentStreamingMessageId.value, incoming: messageId })
      return
    }

    if (isFirst) {
      accumulatedContent.value = chunk
    } else {
      accumulatedContent.value += chunk
    }

    // 实时更新消息内容
    updateChatItem(messageId, {
      content: accumulatedContent.value,
      streaming: true,
      lastUpdated: Date.now()
    })

    console.log('流式内容更新:', {
      messageId,
      chunk,
      totalLength: accumulatedContent.value.length,
      isFirst
    })
  }

  const replaceStreamingContent = (messageId: string, content: string) => {
    if (currentStreamingMessageId.value !== messageId) {
      console.warn('流式消息ID不匹配:', { current: currentStreamingMessageId.value, incoming: messageId })
      return
    }

    accumulatedContent.value = content
    updateChatItem(messageId, {
      content: accumulatedContent.value,
      streaming: true,
      lastUpdated: Date.now()
    })

    console.log('流式内容替换:', {
      messageId,
      contentLength: content.length
    })
  }

  const updateStreamingThoughts = (messageId: string, thought: ThoughtItem) => {
    const message = chatList.value.find(item => item.id === messageId)
    if (!message) return

    const existingThoughts = message.agent_thoughts || []
    const updatedThoughts = [...existingThoughts]
    
    // 检查是否已存在相同的思考步骤
    const existingIndex = updatedThoughts.findIndex(t => 
      t.id === thought.id || (t.position === thought.position && t.tool === thought.tool)
    )

    if (existingIndex !== -1) {
      updatedThoughts[existingIndex] = { ...updatedThoughts[existingIndex], ...thought }
    } else {
      updatedThoughts.push(thought)
    }

    updateChatItem(messageId, { agent_thoughts: updatedThoughts })
  }

  const updateStreamingFiles = (messageId: string, file: VisionFile) => {
    const message = chatList.value.find(item => item.id === messageId)
    if (!message) return

    const existingFiles = message.message_files || []
    const newFile = {
      id: file.upload_file_id || '',
      type: file.type,
      url: file.url,
      belongs_to: 'assistant' as const
    }

    updateChatItem(messageId, {
      message_files: [...existingFiles, newFile]
    })
  }

  const updateWorkflowStatus = (messageId: string, status: WorkflowRunningStatus, workflowRunId?: string) => {
    const message = chatList.value.find(item => item.id === messageId)
    if (!message) return

    const updates: Partial<ChatItem> = {
      workflowProcess: {
        status,
        tracing: message.workflowProcess?.tracing || []
      }
    }

    if (workflowRunId) {
      updates.workflow_run_id = workflowRunId
    }

    updateChatItem(messageId, updates)
  }

  const updateWorkflowTracing = (messageId: string, nodeData: any, status: string) => {
    const message = chatList.value.find(item => item.id === messageId)
    if (!message) return

    const currentTracing = message.workflowProcess?.tracing || []
    const updatedTracing = [...currentTracing]
    
    const existingIndex = updatedTracing.findIndex(t => t.node_id === nodeData.node_id)
    
    if (existingIndex !== -1) {
      updatedTracing[existingIndex] = {
        ...updatedTracing[existingIndex],
        status
      }
    } else {
      updatedTracing.push({
        node_id: nodeData.node_id,
        node_type: nodeData.node_type,
        status
      })
    }

    updateChatItem(messageId, {
      workflowProcess: {
        status: message.workflowProcess?.status || WorkflowRunningStatus.Running,
        tracing: updatedTracing
      }
    })
  }

  const endStreaming = (messageId: string, hasError = false, errorMessage?: string) => {
    if (currentStreamingMessageId.value !== messageId) {
      console.warn('流式消息ID不匹配:', { current: currentStreamingMessageId.value, incoming: messageId })
      return
    }

    const finalContent = hasError 
      ? (errorMessage || '抱歉，发生了错误，请重试。')
      : accumulatedContent.value

    updateChatItem(messageId, {
      content: finalContent,
      streaming: false,
      lastUpdated: Date.now()
    })

    resetStreamingState()

    console.log('流式结束:', {
      messageId,
      hasError,
      finalLength: finalContent.length
    })
  }

  const resetStreamingState = () => {
    currentStreamingMessageId.value = null
    accumulatedContent.value = ''
    isStreaming.value = false
  }

  // 统一的流式数据处理器
  const createStreamingHandlers = (messageId: string) => {
    startStreaming(messageId)

    return {
      onData: (chunk: string, isFirst: boolean, _moreInfo: any) => {
        appendStreamingContent(messageId, chunk, isFirst)
      },

      onThought: (thought: ThoughtItem) => {
        updateStreamingThoughts(messageId, thought)
      },

      onFile: (file: VisionFile) => {
        updateStreamingFiles(messageId, file)
      },

      onMessageEnd: (messageEnd: MessageEnd) => {
        // 处理消息结束事件，获取文件信息
        console.log('消息结束:', messageEnd)
        
        // 查找对应的消息
        const messageIndex = chatList.value.findIndex(item => item.id === messageId)
        if (messageIndex !== -1) {
          const message = chatList.value[messageIndex]
          
          // 从 messageEnd 中提取文件信息
          // messageEnd 可能包含 files 数组或其他文件相关信息
          const messageEndData = messageEnd as any
          
          // 检查多种可能的文件数据来源
          let files: any[] = []
          
          if (messageEndData.files) {
            files = messageEndData.files
          } else if (messageEndData.metadata?.files) {
            files = messageEndData.metadata.files
          } else if (messageEndData.data?.files) {
            files = messageEndData.data.files
          } else if (messageEndData.message_files) {
            files = messageEndData.message_files
          }
          
          // 如果找到文件，添加到消息对象中
          if (files && files.length > 0) {
            console.log('📎 在 messageEnd 中发现文件:', files)
            
            // 更新消息对象，添加文件信息
            const updatedMessage = {
              ...message,
              files: files.map((file: any) => ({
                id: file.id || file.upload_file_id || file.file_id || `file_${Date.now()}`,
                name: file.name || file.filename || file.id,
                type: file.type || file.mime_type || 'application/octet-stream',
                url: file.url || file.download_url || file.file_url,
                size: file.size || file.file_size,
                belongs_to: 'assistant' as const
              }))
            }
            
            // 更新聊天列表中的消息
            chatList.value[messageIndex] = updatedMessage
            
            console.log('✅ 已将文件信息添加到消息:', updatedMessage.files)
          }
          
          // 处理引用信息
          if (messageEndData.metadata?.retriever_resources) {
            const updatedMessage = {
              ...chatList.value[messageIndex],
              citation: messageEndData.metadata.retriever_resources
            }
            chatList.value[messageIndex] = updatedMessage
          }
        }
      },

      onMessageReplace: (messageReplace: MessageReplace) => {
        const content = messageReplace.answer || String(messageReplace)
        replaceStreamingContent(messageId, content)
      },

      onWorkflowStarted: (workflow: WorkflowStartedResponse) => {
        const workflowRunId = workflow.workflow_run_id || workflow.data?.id
        updateWorkflowStatus(messageId, WorkflowRunningStatus.Running, workflowRunId)
      },

      onNodeStarted: (node: NodeStartedResponse) => {
        const nodeData = node.data || node
        updateWorkflowTracing(messageId, nodeData, 'running')
      },

      onNodeFinished: (node: NodeFinishedResponse) => {
        const nodeData = node.data || node
        updateWorkflowTracing(messageId, nodeData, nodeData.status || 'succeeded')
      },

      onWorkflowFinished: (workflow: WorkflowFinishedResponse) => {
        const workflowData = workflow.data || workflow
        const finalStatus = workflowData.status === 'failed' 
          ? WorkflowRunningStatus.Failed 
          : workflowData.status === 'stopped' 
          ? WorkflowRunningStatus.Stopped 
          : WorkflowRunningStatus.Succeeded

        updateWorkflowStatus(messageId, finalStatus)
      },

      onCompleted: (hasError?: boolean) => {
        endStreaming(messageId, hasError)
      },

      onError: (error: string) => {
        endStreaming(messageId, true, `❌ 错误: ${error}`)
      }
    }
  }

  return {
    // 状态
    chatList,
    currentStreamingMessageId,
    isStreaming,
    
    // 计算属性
    currentStreamingMessage,
    
    // 基础操作
    setChatList,
    addChatItem,
    updateChatItem,
    clearChatList,
    
    // 流式数据处理
    createStreamingHandlers,
    endStreaming,
    resetStreamingState
  }
}) 